package cn.aifeix.basic.util;

import cn.aifeix.basic.config.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件工具类
 */
@Component
public class EmailUtil {
    private static JavaMailSenderImpl staticjavaMailSender;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @PostConstruct
    public void init(){
        staticjavaMailSender = javaMailSender;
    }
    public static void sendEmail(String from,String subject,String text,String to) {

        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = staticjavaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            // 设置邮件发送者
            helper.setFrom(from);
            // 设置邮件主题
            helper.setSubject(subject);
            // 设置邮件内容
            helper.setText(text,true);
            // 设置邮件接收方
            helper.setTo(to);
            // 发送邮件
            staticjavaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new BussinessException("邮件发送失败");
        }
    }
}
